<?php
class Application_Model_Portfolio
{
	protected $_dbTable;
	public $_mId;
	public $_mPortfolioName;
	public $_mInitCash;
	public $_mCash;
	public $_mUserId;

	public function getId(){
		return $this->_mId;
	}
	public function setId($value){
		$this->_mId = $value;
		return $this;
	}
	public function getPortfolioName(){
		return $this->_mPortfolioName;
	}
	public function setPortfolioName($value){
		$this->_mPortfolioName = $value;
		return $this;
	}
	public function getInitCash(){
		return $this->_mInitCash;
	}
	public function setInitCash($value){
		$this->_mInitCash = $value;
		return $this;
	}
	public function getCash(){
		return $this->_mCash;
	}
	public function setCash($value){
		$this->_mCash = $value;
		return $this;
	}
	public function getUserId(){
		return $this->_mUserId;
	}
	public function setUserId($value){
		$this->_mUserId = $value;
		return $this;
	}


	public function setDbTable($dbTable){
		if (is_string($dbTable))
			$dbTable = new $dbTable();
		if (!$dbTable instanceof Zend_Db_Table_Abstract)
			throw new Exception('Invalid table data gateway provided');
		$this->_dbTable = $dbTable;
		return $this;
	}
	public function getDbTable(){
		if (null === $this->_dbTable)
			$this->setDbTable('Application_Model_DbTable_Portfolio');
		return $this->_dbTable;
	}
	public function save(Application_Model_Portfolio $old = null){
		$item = $this;
		$data = array();
		if(isset($item->_mId)) $data['id'] = $item->_mId;
		if(isset($item->_mPortfolioName)) $data['portfolio_name'] = $item->_mPortfolioName;
		if(isset($item->_mInitCash)) $data['init_cash'] = $item->_mInitCash;
		if(isset($item->_mCash)) $data['cash'] = $item->_mCash;
		if(isset($item->_mUserId)) $data['user_id'] = $item->_mUserId;

		if($old === null)
			$this->getDbTable()->insert($data);
		else{
			$key = array();
			$old->_mId === null ? $key[] = 'id is NULL' : $key['id = ?'] =  $old->_mId;

			$this->getDbTable()->update($data, $key);
		}
	}
	public function delete(){
		$item = $this;
		$old = $item;
		$key = array();
			$old->_mId === null ? $key[] = 'id is NULL' : $key['id = ?'] =  $old->_mId;

		$this->getDbTable()->delete($key);
	}
	public function fetchAll($where = null, $order = null, $count = null, $offset = null){
		$resultSet = $this->getDbTable()->fetchAll($where, $order, $count, $offset);
		$entries   = array();
		foreach ($resultSet as $row) {
			$item = new Application_Model_Portfolio();
			if(isset($row->id))$item->_mId = $row->id;
			if(isset($row->portfolio_name))$item->_mPortfolioName = $row->portfolio_name;
			if(isset($row->init_cash))$item->_mInitCash = $row->init_cash;
			if(isset($row->cash))$item->_mCash = $row->cash;
			if(isset($row->user_id))$item->_mUserId = $row->user_id;

			$entries[] = $item;
		}
		return $entries;
	}
}
